package com.hangyutech.strelitzia.modules.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hangyutech.strelitzia.modules.dao.ArticlesExtendDao;
import com.hangyutech.strelitzia.modules.entity.Articles;
import com.hangyutech.strelitzia.modules.entity.ArticlesExtend;
import com.hangyutech.strelitzia.modules.service.ArticlesService;
import com.hangyutech.strelitzia.constant.HttpResultCodeEnum;
import com.hangyutech.strelitzia.exception.BizException;
import com.hangyutech.strelitzia.modules.dao.ArticlesDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 文章总表(Articles)表服务实现类
 *
 * @author makejava
 * @since 2020-12-16 16:19:05
 */
@Service("articlesService")
public class ArticlesServiceImpl implements ArticlesService {
    @Resource
    private ArticlesDao articlesDao;


    @Resource
    private ArticlesExtendDao articlesExtendDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Articles queryById(Integer id) {
        return this.articlesDao.queryById(id);
    }

    @Override
    public JSONObject queryContentById(Integer id) {
        Articles obj = this.articlesDao.queryById(id);
        if (Objects.isNull(obj)) {
            return null;
        }
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(obj);
        ArticlesExtend articlesExtend = new ArticlesExtend();
        articlesExtend.setAid(id);
        List<ArticlesExtend> articlesExtendRes = this.articlesExtendDao.queryAll(articlesExtend);
        if (articlesExtendRes != null && articlesExtendRes.size() > 0 && articlesExtendRes.get(0) != null) {
            jsonObject.put("content", articlesExtendRes.get(0).getContent());
            return jsonObject;
        }
        return null;
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<Articles> queryAllByLimit(int offset, int limit) {
        return this.articlesDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param articles 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Articles insert(Articles articles, ArticlesExtend articlesExtend) {
        Date date = new Date(System.currentTimeMillis());
        try {
            articles.setCreatedAt(date);
            int res = this.articlesDao.insert(articles);
            if (res != 1) {
                throw new BizException(HttpResultCodeEnum.RECORD_INSERT_ERROR.getCode(), "无法创建文章");
            }
            articlesExtend.setAid(articles.getId());
            articlesExtend.setCreatedAt(date);
            int resExtend = this.articlesExtendDao.insert(articlesExtend);
            if (resExtend != 1) {
                throw new BizException(HttpResultCodeEnum.RECORD_INSERT_ERROR.getCode(), "无法创建内容");
            }
        } catch (BizException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            throw new BizException();

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new BizException();
        }


        return articles;
    }

    /**
     * 修改数据
     *
     * @param articles 实例对象
     * @return 实例对象
     */
    @Override
    public Articles update(Articles articles, ArticlesExtend articlesExtend) {
        Date date = new Date(System.currentTimeMillis());
        if (!Objects.isNull(articles)) {
            articles.setUpdatedAt(date);
            this.articlesDao.update(articles);
        }
        if (!Objects.isNull(articlesExtend)) {
            articlesExtend.setUpdatedAt(date);
            this.articlesExtendDao.updateByAid(articlesExtend);
        }
        return this.queryById(articles.getId());
    }

    /**
     * 通过主键删除数据 不做直接删除。按软删除处理
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        Date date = new Date(System.currentTimeMillis());
        try {
            Articles article = this.articlesDao.queryById(id);
            article.setDeletedAt(date);
            if (this.articlesDao.update(article) <= 0) {
                throw new BizException(HttpResultCodeEnum.RECORD_DELETE_ERROR.getCode(), "无法删除文章");
            }

            ArticlesExtend articlesExtend = new ArticlesExtend();
            articlesExtend.setAid(id);
            List<ArticlesExtend> articlesExtendRes = this.articlesExtendDao.queryAll(articlesExtend);
            if (articlesExtendRes != null && articlesExtendRes.size() > 0 && articlesExtendRes.get(0) != null) {
                articlesExtendRes.get(0).setDeletedAt(date);
                if (this.articlesExtendDao.update(articlesExtendRes.get(0)) <= 0) {
                    throw new BizException(HttpResultCodeEnum.RECORD_DELETE_ERROR.getCode(), "无法删除内容");
                }
            }
        } catch (BizException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            throw new BizException();

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new BizException();
        }
        return true;
    }


    @Override
    public PageInfo<Articles> search(int pageNum, int pageSize, int status, String title) {
        PageHelper.startPage(pageNum, pageSize);
        if (title.equals("")) {
            title = null;
        }
        Articles searchData = new Articles();
        searchData.setTitle(title);

        if (status != -1) {
            searchData.setStatus(status);
        }
        searchData.setDeletedAt(null);
        List<Articles> results = articlesDao.queryAll(searchData);
        if (results.size() == 0) {
            return new PageInfo<>(results);
        }
        return new PageInfo<>(results);
    }
}